package com.zhan.ielts.web.controller;

import com.zhan.frame.core.dao.BaseService;
import com.zhan.frame.core.web.controller.BaseControllerImpl;
import com.zhan.frame.core.web.domain.CustomResult;
import com.zhan.frame.core.web.domain.Result;
import com.zhan.frame.core.web.domain.Result.Status;
import com.zhan.ielts.domain.AdBundle;
import com.zhan.ielts.domain.Param;
import com.zhan.ielts.domain.query.AdBundleQuery;
import com.zhan.ielts.service.AdBundleService;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.util.TextUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/ad/bundle")
public class AdBundleController extends BaseControllerImpl<AdBundle, AdBundleQuery> {

    private Logger log = LoggerFactory.getLogger(AdBundleController.class);

    @Autowired
    private AdBundleService adBundleService;

    @Override
    protected BaseService<AdBundle> getBaseService() {
        return adBundleService;
    }

    @ResponseBody
    @RequestMapping(value = "/fetch", method = RequestMethod.POST)
    public CustomResult fetchTreasureChest(String bundleId, String type) {
        log.debug("获取广告绑定信息开始");
        Map<String, Integer> map = new HashMap<String, Integer>();
        List<AdBundle> adBundleList = null;
        AdBundle adBundle = null;

        int page = 0;
        int pageSize = 1;
        Sort sort = new Sort(Direction.ASC, "review_version");
        Pageable pageable = new PageRequest(page, pageSize, sort);

        try {
            AdBundle query = new AdBundle();
            query.setBundleId(bundleId);
            query.setType(type);

            adBundle = adBundleService.queryOne(query);
        } catch (Exception e) {
            e.printStackTrace();
            log.debug("获取广告绑定信息失败");
            map.put("errCode", 1001);
            return new CustomResult(0, "系统错误, 获取广告绑定信息失败！", map);

        }
        log.debug("获取广告绑定信息结束");

        if (adBundle == null) {
            return new CustomResult(1, "", map);
        }
        return new CustomResult(1, "", adBundle);
    }

    @ResponseBody
    @RequestMapping(value = "/recordClick", method = RequestMethod.POST)
    public Result recordClickTimes(String id, String type) {
        log.debug("广告绑定点击次数统计开始");
        if (StringUtils.isEmpty(id)) {
            return new Result(Status.ERROR, "id不能为空");
        } else if (StringUtils.isEmpty(type)) {
            return new Result(Status.ERROR, "type不能为空");
        }
        try {

            AdBundle adBundle = new AdBundle();
            adBundle.setId(id);
            Long count = adBundleService.queryCount(adBundle);
            if (count < 1) {
                log.debug("id不存在");
                return new Result(Status.ERROR, "id不存在");
            }

            Param param = new Param();
            param.setType("banner");
            param.setParamName(id + "-" + type + "-times");
            adBundleService.recordClickTimes(param);

            log.debug("广告绑定点击次数统计结束");
        } catch (Exception e) {
            log.debug("广告绑定点击次数统计失败");
            return new Result(Status.ERROR, "系统错误, 广告绑定点击次数统计失败！");
        }
        return new Result(Status.OK, "");
    }


    @Override
    @RequestMapping(method = RequestMethod.GET)
    public ModelAndView selectList(AdBundleQuery query, @PageableDefault Pageable pageable) {
        if (!TextUtils.isEmpty(query.getBundleIdLike())) {
            if (query.getBundleIdLike().equalsIgnoreCase("小站雅思")) {
                query.setBundleIdLike("com.zhan.ieltstiku");
            } else if (query.getBundleIdLike().equalsIgnoreCase("雅思单词")) {
                query.setBundleIdLike("com.zhan.ieltsword");
            }
        }

        Page<AdBundle> page = adBundleService.queryPageList(query, pageable);
        ModelAndView mav = new ModelAndView("/ad/bundle/listBundle", "page", page);
        mav.addObject("query", query);
        return mav;
    }

    @ResponseBody
    @RequestMapping(value = "/addOne", method = RequestMethod.POST)
    public Result addOne(AdBundle entity, @RequestParam(value = "file", required = false) MultipartFile file) {
        if(file==null){
            throw new IllegalArgumentException("图片不能这空");
        }
        entity.setUpdateTime(new Timestamp(new Date().getTime()));
        String adId = adBundleService.getMaxAdBundleBytype(entity.getType());
        if (adId == null) {
            adId = "ad_1";
        } else {
            int index = Integer.parseInt(adId) + 1;
            adId = "ad_" + index;
        }
        if(entity.getReviewVersion() == null) {
            entity.setReviewVersion("");
        }
        entity.setAdId(adId);
        adBundleService.uploadImage(entity,file);
        return new Result(Result.Status.OK, "成功");
    }

    @ResponseBody
    @RequestMapping(value = "/editOne", method = RequestMethod.POST)
    public Result editOne(AdBundleQuery entity, @RequestParam(value = "file", required = false) MultipartFile file) {
        entity.setUpdateTime(new Timestamp(new Date().getTime()));
        if(entity.getIsUpdateAdId().equals("1")){
            String adId = adBundleService.getMaxAdBundleBytype(entity.getType());
            if (adId == null) {
                adId = "ad_1";
            } else {
                int index = Integer.parseInt(adId) + 1;
                adId = "ad_" + index;
            }
            entity.setAdId(adId);
        }
        adBundleService.uploadImage(entity,file);
        return new Result(Result.Status.OK, "成功");
    }


    @ResponseBody
    @RequestMapping(value = "/changeDialog", method = RequestMethod.POST)
    public Result change(@RequestBody List<JSONObject> array) {
        try {
            for (int i = 0; i < array.size(); i++) {
                JSONObject jsonObject = array.get(i);
                AdBundle adBundle = new AdBundle();
                adBundle.setBundleId(jsonObject.getString("bundleId"));
                adBundle.setPosition("dialog");
                adBundle.setType(jsonObject.getString("platform"));
                AdBundle bean = adBundleService.queryOne(adBundle);
                if (null != bean) {
                    String adId = bean.getAdId();
                    int id = Integer.parseInt(adId.split("_")[1]);
                    if (jsonObject.getInt("id") != id) {
                        adBundleService.deleteById(bean.getId());
                        adBundle.setReviewVersion(bean.getReviewVersion());
                        insertAdBundle(adBundle, jsonObject);
                    }
                } else {
                    adBundle.setReviewVersion("");
                    insertAdBundle(adBundle, jsonObject);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(Status.ERROR, "更改失败");
        }
        return new Result(Status.OK, "更改成功！");
    }

    private void insertAdBundle(AdBundle adBundle, JSONObject jsonObject) {
        adBundle.setLink(jsonObject.getString("link"));
        adBundle.setLinkType(jsonObject.getInt("linkType"));
        adBundle.setName(jsonObject.getString("name"));
        adBundle.setImage(jsonObject.getString("imageLink"));
        adBundle.setAdId("ad_" + jsonObject.getInt("id"));
        adBundle.setUpdateTime(new Timestamp(new Date().getTime()));
        adBundleService.insert(adBundle);
    }
}
